package com.yougou.ui.mine;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.yougou.R;
import com.yougou.base.BaseActivity;
import com.yougou.data.model.Goods;
import com.yougou.ui.mine.adapter.FavoriteAdapter;
import com.yougou.ui.product.ProductDetailActivity;
import com.yougou.utils.FavoriteManager;
import com.yougou.utils.ToastUtils;

import java.util.List;

public class FavoriteActivity extends BaseActivity {
    
    private Toolbar mToolbar;
    private RecyclerView mRecyclerView;
    private View mLayoutEmpty;
    
    private FavoriteAdapter mAdapter;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_favorite);
        initView();
        initData();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        // 每次返回时刷新收藏列表
        loadFavorites();
    }
    
    @Override
    protected void initView() {
        mToolbar = findViewById(R.id.toolbar);
        mToolbar.setNavigationOnClickListener(v -> finish());
        
        mRecyclerView = findViewById(R.id.rv_favorites);
        mLayoutEmpty = findViewById(R.id.layout_empty);
        
        // 设置网格布局
        GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
        mRecyclerView.setLayoutManager(layoutManager);
        
        mAdapter = new FavoriteAdapter();
        mRecyclerView.setAdapter(mAdapter);
        
        // 商品点击事件
        mAdapter.setOnItemClickListener(goods -> {
            Intent intent = new Intent(this, ProductDetailActivity.class);
            intent.putExtra(ProductDetailActivity.EXTRA_GOODS_ID, goods.getGoodsId());
            startActivity(intent);
        });
        
        // 删除收藏事件
        mAdapter.setOnDeleteClickListener((goods, position) -> {
            FavoriteManager.removeFavorite(goods.getGoodsId());
            mAdapter.removeItem(position);
            ToastUtils.show(this, "已取消收藏");
            
            // 检查是否为空
            if (mAdapter.getItemCount() == 0) {
                showEmpty();
            }
        });
    }
    
    @Override
    protected void initData() {
        loadFavorites();
    }
    
    
    private void loadFavorites() {
        List<Goods> favorites = FavoriteManager.getFavorites();
        
        if (favorites != null && !favorites.isEmpty()) {
            mAdapter.setData(favorites);
            showList();
        } else {
            showEmpty();
        }
    }
    
    
    private void showList() {
        mRecyclerView.setVisibility(View.VISIBLE);
        mLayoutEmpty.setVisibility(View.GONE);
    }
    
    
    private void showEmpty() {
        mRecyclerView.setVisibility(View.GONE);
        mLayoutEmpty.setVisibility(View.VISIBLE);
    }
}

